package com.xmut.mall.auth.service.impl;

import com.xmut.mall.auth.constant.AuthConstant;
import com.xmut.mall.auth.feign.ThirdPartyFeignService;
import com.xmut.mall.auth.service.SmsService;
import com.xmut.mall.auth.utils.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    /**
     * 发送验证短信
     *
     * @param phone
     */
    @Override
    public RespBean sendCode(String phone) {
        // 服务器端短信防刷
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            // 如果redis查找该手机号码的结果不是空
            return RespBean.error("当前短信仍在有效期内请勿重复发送");
        }
        // 如果redis没找到该手机号存入的验证码则发送
        // 初始化验证码 随机的四位数
        String code = String.valueOf(new Random().nextInt(9999));
        // 发送短信
        RespBean respBean = thirdPartyFeignService.sendCode(phone, code);
        if (respBean.getCode() == 201) {
            // 发送成功 向redis中存储code和手机号 有效期30分钟
            redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, code, 1800000l, TimeUnit.MILLISECONDS);
        }
        return RespBean.success("短信发送成功");
    }
}
